package org.iteam.core.utils;
import java.io.Reader;
import java.io.StringReader;

import org.iteam.core.lucene.CharReader;
import org.iteam.core.solr.HTMLStripCharFilter;

public class HtmlFilter {

	public static String filter(String content) {
		StringBuffer result = new StringBuffer();
		Reader in = null;
		try {
			in = new HTMLStripCharFilter(CharReader.get(new StringReader(content)));
			int num = 0;// 记录 “<”的数量
			int ch;
			char temp = 0;// 用于判断上一个字符。 如果是空格，则‘>’不再生成空格

			while ((ch = in.read()) != -1) {
				char charch = (char) ch;
				switch (ch) {
				case 60:// '<'
					num++;
					break;
				case 62:// '>'
					num = num > 0 ? num - 1 : 0;
					if (num == 0 && temp != 32) {
						result.append(" ");
						temp = 32;
					}
					break;
				default:
					if (num == 0) {
						result.append(charch);
						temp = charch;
					}
					break;
				}
			}
			in.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
			}
		}
		return result.toString();
	}
}
